package com.lxw.demo.component;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.List;


@WebFilter(urlPatterns = "/*")
public class MyFilter implements Filter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${token.header}")
    private String header;
    @Value("${token.prefix}")
    private String prefix;
    @Value("${token.exclude}")
    private String exclude;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("进来了吗");


        HttpServletRequest request = (HttpServletRequest) servletRequest;;
        List<String> excludeList = Arrays.asList(exclude.split(","));
        if(excludeList.contains(request.getRequestURI())){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        String token = request.getHeader(header);

//        Object key = redisTemplate.opsForValue().get(token);
        System.out.println("token需要检测");
        if(token == null || token.equals("")){
            System.out.println("token没有通过检测");
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }


    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
